define(['template/permissionGrounp/indexTpl','common','wx','wx.ajax','wx.tpl','wx.pop','vendor/bootstrap-typeahead','vendor/jquery.dataTables'],function(tpl,common,wx){
	var windowId;
    var permission = {};
    function init(id){
    	windowId = wx.stringToJson(id).windowId;
        var t = new Date().getTime();
        $.when(
            $.ajax('/res/css/jquery.dataTables.min.css'),
            $.ajax('/res/css/permission.css?t='+t)
            ).done(function(tableCss,perCss){
                $('<style type="text/css">').append(perCss,tableCss).appendTo('head');
                setup();
            });
	}

    function setup(){
        wx.sendData('/permission/get-list',function(data){
            $('#window-frame-permissionGrounp').html(tpl.grounp);
            $('#Js-grounpTable').DataTable({
                data:data.result,
                columns: [
                    { data: 'name' , "bSortable": false},
                    { data: 'ctr' , "bSortable": false}
                ],
                columnDefs: [
                    {
                      targets: [1],
                      render: function(data, type, full) {
                        return "<a class='Js-permission-edit' data-id='"+full.id+"' href='javascript:;'>修改</a>";
                      }
                    }
                  ],
                language:common.dataTableText
            });
            $('#Js-grounpTable_length').append(tpl.grounpAdd);

            pageEvent();
        });
    }

    function pageEvent(){
        $('#Js-permission-add').click(function() {
            addEvnet();
        });
        $('.Js-permission-edit').click(function() {
            wx.sendData('/permission/get','id='+$(this).data('id'),addEvnet);
        });
    }

    function addEvnet(data){
        data = data ||{result:{content:[]}};
        $('#window-frame-permissionGrounp').html(wx.tpl(tpl.addContent,{list:shortcut,item:data.result}));
        $('#Js-addBack').click(setup);
        $('input[type="submit"]').click(function() {
            var name = $('input[name="grounpName"]').val(),
                id = $(this).data('id')?'id='+$(this).data('id')+'&':'',
                selectData = {};
            if(!name){
                $('#Js-permission-error').text('请输入组名称');
                return;
            }
            $('.Js-item').each(function(){
                selectData[$(this).data('id')] = [
                    $(this).find('input[name="read"]').prop('checked')?1:0,
                    $(this).find('input[name="write"]').prop('checked')?1:0
                ];
            });
            wx.sendData('/permission/save',id+'name='+name+'&content='+JSON.stringify(selectData)).success(function(){
                setup();
            }).fail(function(data){
                wx.alert(data.info);
            });
        });
    }
    permission.init = init;
    return permission;
});